-------------------------------------------------------------------
--                       Chat System                             --
-------------------------------------------------------------------
-- Window used for chat.
function AmB.Win.CreateChat()
	-----------------------------
	--      Control Creation   --
	-----------------------------
	local SCRH = ScrH()
	local SCRW = ScrW()

	-- Frame for everything and stuff
	local frame = vgui.Create("AmBFrame")
	frame:SetMargin(4, 4)


	local dummy = vgui.Create("AmBTextControl")
	dummy:SetText("testlineheight")
	local lineheight = dummy:GetLineHeight()
	dummy:Remove()


	local height = math.Round( (SCRH/4) / lineheight ) * lineheight  ----math.Round( angle.yaw / 45 ) * 45
	local width = SCRW/3
	
	frame:SetPos(35, SCRH-(SCRH /2))
	frame:SetSize(width, height) -- w, h
	
	frame._Active = false

   -- Splitter to seperate parts of the chat window
   local layout = vgui.Create("AmBContentSplitter", frame:GetInterior())
   layout:SetDocking(true)
   layout:SetSplitters(false, { 200 })
   frame._Layout = layout

   -- List/log of chat items
   local list = vgui.Create("AmBList", layout:GetArea(1))
   list:SetDocking(true)
   list:SetCallbacks(function(Index, Control, UserData)
			local itemfx = vgui.Create("AmBEffectsPanel", Control)
			itemfx:SetDocking(true)
			local cols = Freeze(ThemeVar("chatbox_message_colors"))
			itemfx:SetPanelColor(cols[((Index + 1) % #cols) + 1])
			itemfx:SetFadeFactor(ThemeVar("chatbox_message_fade_speed"))

			local textcontrol = vgui.Create("AmBTextControl", itemfx)
			textcontrol:SetDocking(true)
			textcontrol:SetText(UserData.Message)
			
			UserData._FXPanel = itemfx
			UserData._TextPanel = textcontrol
			UserData._Faded = false
			
			if UserData._Alpha != nil then
				itemfx:SetCurrentAlpha(UserData._Alpha)
			end
		end, function(Index, Control, UserData)
			UserData._Alpha = UserData._FXPanel:GetCurrentAlpha()
			return false
		end)
   frame._List = list
	
	-- List fading out
	local fadetime = ThemeVar("chatbox_message_fade_time")
	local fading = ThemeVar("chatbox_message_use_fading")
	local oldthink = frame.PanelThink
	local newthink = function(frame)
			oldthink(frame)
			if Freeze(fading) then
				local curtime = CurTime()
				frame._List:ForEach(function(Index, Control, UserData)
					local alpha = math.Clamp( math.floor( ( (UserData.Time + fadetime)-curtime )*255 )  , 0, 255 )
					if not frame._Active then
						/*if UserData._Faded then
							UserData._FXPanel:SetCurrentAlpha(0)
						end
						UserData._FXPanel:SetTargetAlpha(0)
						if UserData._FXPanel:GetCurrentAlpha() == 0 then
							UserData._Faded = true
						end*/
						UserData._FXPanel:SetCurrentAlpha(alpha) -- just a quick fix to fix a bug (some chat msgs not fading when another msg of the same person was visible)
						UserData._FXPanel:SetTargetAlpha(alpha)
					else
						UserData._FXPanel:SetCurrentAlpha(255)
						UserData._FXPanel:SetTargetAlpha(255)
						if alpha <= 254 then -- make sure we dont fade out other chats messages that arnt ready yet
							UserData.Time = curtime - fadetime + 1  --- Make it fade out, and not apear ther one second, and not the next whe they have spoke
						end
					end
				end)
			end
		end
	frame.PanelThink = newthink

   -- Text entry and padding for text entry
	local fx = vgui.Create("AmBEffectsPanel", layout:GetArea(2))
	fx:SetDocking(true)
	frame._FX = fx
	
   local padder = vgui.Create("AmBPaddedPanel", fx:GetInterior())
	local pint = ThemeVar("chatbox_textentry_interior_color")
	local pout = ThemeVar("chatbox_textentry_border_color")
   padder:SetDocking(true)
   padder:SetPaddingColor(pint, pout)
   padder:GetInterior():SetPanelColor(pint)

   local textentry = vgui.Create("AmBTextControl", padder:GetInterior())
   textentry:SetDocking(true)
   textentry.TextColor = Color(0, 0, 0, 255)
   frame._TextEntry = textentry
	
	function layout:OnAreaResize(Index, NewSize, FullSize)
		if Index == 2 then
			layout:SetSplitter(1, FullSize - NewSize)
			return true
		end
		return false
	end

   -----------------------------
   --       Chat Logic        --
   -----------------------------
   function frame:OnUpdateChat(Text)
		self._TextEntry:SetText(Text)
		if string.len(Text) > 0 then
			self._FX:Show()
		else
			self._FX:Hide()
		end
   end

   function frame:OnStartChat(TeamChat)
		self:Focus()
		self._TextEntry:SetText(" ")
		self._FX:Show()
		self._Active = true
   end

   function frame:OnFinishChat()
		self:Fade()
		self._FX:Hide()
		self._Active = false
   end

   function frame:OnPlayerChat(Player, Text, Team, Dead)
		local String = ""
		local StringCol = Color(255, 255, 255, 255)
		local TeamCol = team.GetColor(Player:Team())
		local TeamColTint = Color(255,255,255,255) --Color( math.Clamp(TeamCol.r*10,0,255), math.Clamp(TeamCol.g*10,0,255), math.Clamp(TeamCol.b*10,0,255), 255 )
		local stringtable = { }
		if Dead then
			String = "[DEAD] "
			StringCol = Color(255, 0, 0, 255)
			table.insert(stringtable, {Text = String, Color = StringCol})
		 end

      if Team then
			String = "[TEAM] "
			StringCol = TeamCol
			TeamColTint = TeamCol
			table.insert(stringtable, {Text = String, Color = StringCol})
      end

		table.insert(stringtable, {Text = Player:GetName(), Color = TeamCol})
		table.insert(stringtable, {Text = ": " .. Text, Color = TeamColTint})
      self._List:InsertItem(20, {Time = CurTime(), Message = stringtable})
   end
	
	function frame:OnChatText(PI, Name, Text, Type)
		if Text != nil then
		   local stringtable = { }
			local Col = Color(255,50,50,255)
			if Type == "none" then
				Col = Color(255,128,0,255)
			end
			Msg(Type)
			table.insert(stringtable, {Text = Text, Color = Col})
         self._List:InsertItem(20, {Time = CurTime(), Message = stringtable})
		end
	end
	
	
	function frame:Fade()
		self._FX:Hide()
		self._List:ScrollDown()
		self._List:GetScrollFX():Hide()
		self:SetAlpha(255)
	end
	
	function frame:Focus()
		self._List:GetScrollFX():Show()
		self:SetAlpha(255)
	end

   -- Return new chat frame
	frame:Fade()
	return frame
end

-- Links a chat window created with CreateChat to 
-- the default chat system, effectively replacing it.
-- Pass nil as the frame to unlink the chat system.
function AmB.Win.LinkChat(Frame)
   if Frame != nil then
      hook.Add("ChatTextChanged", "AmBUpdateChat", function(Text) Frame:OnUpdateChat(Text) end)
      hook.Add("FinishChat", "AmBCloseChat", function() Frame:OnFinishChat(Text) end)
      hook.Add("StartChat", "AmBOpenChat", function(Team) Frame:OnStartChat(Team) return true end)
      hook.Add("OnPlayerChat", "AmBOnPlayerChat", function(Player, Text, Team, Dead) Frame:OnPlayerChat(Player, Text, Team, Dead) end)
      hook.Add( "ChatText", "AmBChatText", function(PI, Name, Text, Type) Frame:OnChatText(PI, Name, Text, Type) end)
   else
      hook.Remove("ChatTextChanged", "AmBUpdateChat")
      hook.Remove("FinishChat", "AmBCloseChat")
      hook.Remove("StartChat", "AmBOpenChat")
      hook.Remove("OnPlayerChat", "AmBOnPlayerChat")
      hook.Remove("ChatText", "AmBChatText")
   end
   AmB.Win._LinkedChatFrame = Frame
end


--Start
hook.Add("Initialize", "AmBChatInitialize", function()
	AmB.Win.LinkChat(AmB.Win.CreateChat())
end)

--Console commands
concommand.Add("amb_chatbox_enable", function(Player, Command, Args) 
	AmB.Win.LinkChat(AmB.Win.CreateChat())
end)
concommand.Add("amb_chatbox_disable", function(Player, Command, Args)
	local frame = AmB.Win._LinkedChatFrame
	if frame != nil then
		frame:Remove()
	end
	AmB.Win.LinkChat(nil)
end)